import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:string_validator/string_validator.dart';

import '../../common/config.dart';
import '../../common/mixin/adjust.dart';
import '../../common/strategy/strategy.dart';
import '../../generated/assets.dart';
import '../../router/extension/router.dart';

/// The splash screen
class SplashScreen extends StatefulWidget {
  /// Constructs a [SplashScreen]
  const SplashScreen({super.key});

  @override
  State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen>
    with WidgetsBindingObserver {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        alignment: Alignment.center,
        children: [
          Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Image.asset(Assets.iconLogo, width: 210, height: 210),
                Text(
                  Config.appName,
                  style: Theme.of(context).textTheme.headlineMedium?.copyWith(
                        fontWeight: FontWeight.bold,
                        fontSize: 20,
                      ),
                  textAlign: TextAlign.center,
                ),
              ],
            ),
          ),
          const Positioned(
            bottom: 30,
            child: SpinKitWave(color: Colors.white, size: 30.0),
          ),
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    goHome();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.inactive:
        break;
      case AppLifecycleState.resumed:
        Adjust.onResume();
        break;
      case AppLifecycleState.paused:
        Adjust.onPause();
        break;
      case AppLifecycleState.detached:
        break;
      case AppLifecycleState.hidden:
        break;
    }
  }

  Future<void> goHome() async {
    await context.read<Config>().init();

    int start = DateTime.now().millisecondsSinceEpoch;
    List<String> urls = await strategy.getStrategy();
    int count = await Config.getLaunchCount();
    String? url;
    if (urls.isNotEmpty) {
      url = urls[count % urls.length];
    }
    bool isUrl = isURL(url);
    int end = DateTime.now().millisecondsSinceEpoch;
    int diff = 2000 - (end - start);

    Future.delayed(Duration(milliseconds: diff < 0 ? 0 : diff)).then((value) {
      if (isUrl) {
        context.web(url!);
        // context.web("https://flutter.dev");
        // context.go('/home');
      } else {
        context.go('/home');
      }
    });
  }
}
